package com.example.day01_weather.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.day01_weather.R;
import com.example.day01_weather.adapter.Adapter2;
import com.example.day01_weather.adapter.WeatherAdapter;
import com.example.day01_weather.bean.CityBean;
import com.example.day01_weather.bean.LatitudeBean;
import com.example.day01_weather.bean.WeatherBean;
import com.example.day01_weather.mvp.presenter.Presenter;
import com.example.day01_weather.mvp.view.IWeather;
import com.example.day01_weather.net.HttpManger;
import com.example.day01_weather.utils.LocationUtils;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WeatherActivity extends AppCompatActivity implements IWeather.IView {

    @BindView(R.id.tv_item)
    TextView tvItem;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv)
    RecyclerView rv;
    private ArrayList<WeatherBean.ResultBean.DailyBean> beans;
    private WeatherAdapter adapter;
    private Presenter presenter;
    private CityBean cityData;
    private  String city;
    private ArrayList<CityBean.ResultBean> cityList=new ArrayList<>();
    //申请的权限
    private static final String[] mPermissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION
            ,Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE};
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        ButterKnife.bind(this);
        initView();
        requestPermissions();
        initData();
    }
    private void requestPermissions() {
        if (PermissionsUtil.hasPermission(this,mPermissions)) {
            //有访问权限
            initLocation();
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    //用户授予了访问权限
                    initLocation();
                }
                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    //用户拒绝了访问的申请
                }
            }, mPermissions);
        }
    }





    private void initLocation() {
        LocationUtils.getInstance(this).setAddressCallback(new LocationUtils.AddressCallback() {
            @Override
            public void onGetAddress(Address address) {
                String countryName = address.getCountryName();//国家
                String adminArea = address.getAdminArea();//省
                String locality = address.getLocality();//市
                String subLocality = address.getSubLocality();//区
                String featureName = address.getFeatureName();//街道
                Log.e("定位地址",countryName+adminArea+locality+subLocality+featureName);
            }

            @Override
            public void onGetLocation(double lat, double lng) {
                Log.e("定位经纬度",lat+"///1111111///"+lng+"");

                HttpManger.getInstance().getLanApiService().getLatitude(lat,lng)
                        .enqueue(new Callback<LatitudeBean>() {
                            @Override
                            public void onResponse(Call<LatitudeBean> call, Response<LatitudeBean> response) {
                                Log.e("TAG", "onResponse: "+response.body().getData().toString());

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(WeatherActivity.this, response.body().getData().toString(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                            @Override
                            public void onFailure(Call<LatitudeBean> call, Throwable t) {

                            }
                        });
            }
        });
    }

    private void initData() {
        presenter = new Presenter(this);
        presenter.getCityData();
    }

    private void initView() {
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));



        beans = new ArrayList<>();
        adapter = new WeatherAdapter(beans, this,city);
        rv.setAdapter(adapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0,0,0,"切换");
        menu.add(0,1,0,"定位");
        menu.add(0,2,0,"空气质量");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case 0:
                pop();
                break;
            case 1:
                dingwei();
                break;
            case 2:
                startActivity(new Intent(WeatherActivity.this,TemperatureActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void dingwei() {
        requestPermissions();

    }

    private void pop() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.pop, null);
        final PopupWindow popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());

        popupWindow.setOutsideTouchable(true);
        RecyclerView pop = inflate.findViewById(R.id.popp);
        pop.setLayoutManager(new LinearLayoutManager(this));
        pop.addItemDecoration(new DividerItemDecoration(this,1));

        Adapter2 adapter2 = new Adapter2(cityList, this);
        pop.setAdapter(adapter2);

        adapter2.setOnClickListener(new Adapter2.OnClickListener() {
            @Override
            public void ClickListener(int position) {
                Map<String,String> map = new HashMap<>();
                map.put("city", cityList.get(position).getCity());
                city=cityList.get(position).getCity();
                presenter.getWeatherData(map);
                popupWindow.dismiss();
            }
        });
        popupWindow.showAsDropDown(toolbar);
    }

    @Override
    public void getCitySuccess(CityBean cityBean) {
        cityData = cityBean;
        cityList.addAll(cityBean.getResult());
        if(cityData != null){
            Map<String,String> map = new HashMap<>();
            city = cityData.getResult().get(0).getCity();
            map.put("city", city);
            presenter.getWeatherData(map);
        }
    }


    @Override
    public void getWeatherSuccess(WeatherBean weatherBean) {
        if (beans!=null){
            beans.clear();
        }

        beans.addAll(weatherBean.getResult().getDaily());
        adapter.notifyDataSetChanged();
    }

    @Override
    public void tips(String error) {
        Log.e("TAG", "tips: "+error );
    }
}